// pages/euqip/equip.js
const {
  API,
  defaultPage,
  equipStatusEnum,
  CLINIC_MANAGER_CODE
} = require('../../utils/const.js');
const {
  formVaildate,
  checkCount
} = require('../../utils/formCheckUtil.js');
const {
  getRequest,
  postRequest
} = require('../../utils/request.js');
const re = require('../../utils/request.js');
const {
  EuipFormRoles
} = require('../../utils/rulse.js');
const {
  hasRole
} = require('../../utils/userUtil.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    app: app,
    showAddForm: false,
    equipList: [],
    listOperateBtn: [{
      text: '报废'
    }],
    selectEquipList: [],
    showDisCardForm: false,
    showLoseForm: false,
    bgTextStyle: 'dark',
    scrollTop: '200rpx',
    bgColor: '#ff0000',
    bgColorTop: '#00ff00',
    bgColorBottom: '#0000ff',
    nbTitle: '标题',
    nbLoading: false,
    nbFrontColor: '#000000',
    nbBackgroundColor: '#ffffff',
    equipStatusEnum: equipStatusEnum,
    activitiBar: 1,
    searchParams: {},
    pageParams: {
      ...defaultPage,
      size: 20
    },
    cateListData: [],
    disCardForm: {},
    lossForm: {},
    currentOperateItem: {},
    current: 1,
    size: 990,
    total: 0,
    hasManagerRole: false,
    diBtn: [{
      text: "取消"
    }, {
      text: "确认"
    }, ]
  },
  onDiscardBtnClock: function (e) {
    const that = this;
    console.log("disCardForm", this.data.disCardForm)
    switch (e.detail.index) {
      case 0: // 取消   
        that.closeDiscardForm()
        break;
      case 1:
        // if(disCardForm)
        if (checkCount(this.data.disCardForm.count) <= 0) {
          return
        }
        this.confirmUse("DISCARD", this.data.currentOperateItem, this.data.disCardForm).then(res => {
          if (res) {
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              duration: 1000,
              success: () => {
                that.setData({
                  currentOperateItem: {}
                })
                that.fetchSelectAbleList();
              }
            })
          }
          that.closeDiscardForm()
        })
        break;
    }
  },
  onInputDiscardRemark: function (e) {
    const val = e.detail.value;
    this.setData({
      'disCardForm.remark': val
    })
  },
  onInputLossRemark: function (e) {
    const val = e.detail.value;
    this.setData({
      'lossForm.remark': val
    })
  },
  resetForm: function (formName) {
    console.log("closeForm")
    this.setData({
      disCardForm: {
        count: undefined,
        remark: undefined
      },
      lossForm: {
        count: undefined,
        remark: undefined
      }
    })
  },
  onInputDiscardCount: function (e) {
    const val = e.detail.value;
    console.log("e", e)
    this.setData({
      'disCardForm.count': val
    })
  },
  onInputLossCount: function (e) {
    const val = e.detail.value;
    console.log("e", e)
    this.setData({
      'lossForm.count': val
    })
  },
  onLossBtnClock: function (e) {
    const that = this;
    // console.log("disCardForm", this.data.disCardForm)
    switch (e.detail.index) {
      case 0: // 取消   
        that.closeLossForm()
        break;
      case 1:
        if (checkCount(this.data.lossForm.count) <= 0) {
          return
        }
        this.confirmUse("LOSS",
            this.data.currentOperateItem,
            this.data.lossForm)
          .then(res => {
            if (res) {
              wx.showToast({
                title: '操作成功',
                icon: 'success',
                duration: 1000,
                success: () => {
                  that.setData({
                    currentOperateItem: {}
                  })
                  that.fetchSelectAbleList();
                }
              })
            }
            that.closeLossForm()
          })
        break;
    }
  },
  closeDiscardForm: function () {
    this.setData({
      showDisCardForm: false
    })
    this.resetForm();
  },
  closeLossForm: function () {
    this.setData({
      showLoseForm: false
    })
    this.resetForm
  },
  oncClearClick: function () {
    this.setData({
      searchParams: {
        ...this.data.searchParams,
        equipStatus: null
      }
    })
  },
  onPickerChange: function (e) {
    const selectIndex = e.detail.value;
    const eqquipStatusList = this.data.equipStatus;
    const selectName = eqquipStatusList[selectIndex].name;
    console.log(selectName);
    this.setData({
      searchParams: {
        ...this.data.searchParams,
        equipStatus: selectName
      }
    })
    this.fetchSelectAbleList();
  },
  selected: function (list, id) {
    console.log('&&&', list, id)
    return list;
  },
  hasManagerRolePermission: function () {
    const hasRoles = hasRole(CLINIC_MANAGER_CODE)
    this.setData({
      hasManagerRole: hasRoles
    })
    // "clinic:manger"
    // getUser
  },
  equipAddFormSubmit: function (e) {

    const formData = e.detail.value;
    formVaildate(formData, EuipFormRoles).then(reslut => {
      console.log("reslut", reslut)
      postRequest(API.createEquip, formData).then(res => {
        if (res) {
          this.setData({
            showAddForm: false
          })
          this.fetchSelectAbleList();
        }
      })
    }).catch(reason => {
      wx.showToast({
        title: reason,
        icon: 'error'
      })
    })

  },
  onFormRest: function () {
    this.setData({
      showAddForm: false
    })
  },
  onAddClose: function () {
    this.setData({
      showAddForm: false
    })
  },
  onAddClick: function () {
    this.setData({
      showAddForm: true
    })
    // wx.navigateTo({
    //   url: '/pages/equipAddForm/form',
    // })
  },
  onLongTapEquip: function (e) {
    if (!this.data.hasManagerRole) {
      return;
    }
    const that = this;
    const item = e.currentTarget.dataset.value;
    this.setData({
      currentOperateItem: item
    })
    wx.showActionSheet({
      itemList: ['报废', '丢失'],
      success(res) {
        const {
          tapIndex
        } = res;
        if (tapIndex === 0) {
          that.setData({
            showDisCardForm: true
          })
        }
        if (tapIndex === 1) {
          that.setData({
            showLoseForm: true
          })
        }
        if (tapIndex === 2) {

        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },
  onReachBottom() {
    console.log("reach")
  },
  doListQuery(e) {
    const params = e.detail;

    const searchData = {
      ...params,
      ...this.data.searchParams,
      ...this.data.pageParams,
     
    }
    getRequest(API.listInfo, searchData).then(res => {

      console.log("result", res);
      this.setData({
        // total: res.total,
        // size: res.size,
        // current: res.current,
        equipList: res
      })
    })

  },
  fetchSelectAbleList() {
    this.setData({
      equipList: []
    })
    const searchData = {
      ...this.data.searchParams,
      ...this.data.pageParams
    }
    getRequest(API.listInfo, searchData).then(res => {

      console.log("result", res);
      this.setData({
        // total: res.total,
        // size: res.size,
        // current: res.current,
        equipList: res
      })
    })

  },
  onEquipClick: function (e) {
    var selectItem = e.currentTarget.dataset.value;
    var selectEquipList = this.data.selectEquipList;
    if (selectEquipList.indexOf(selectItem.id) == -1) {
      selectEquipList.push(selectItem.id);
    } else {
      selectEquipList.splice(selectEquipList.indexOf(selectItem.id), 1);
    }

    this.setData({
      selectEquipList: [...selectEquipList]
    })
  },
  useEquip() {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetchAllEquipStatus();

  },
  fetchAllEquipStatus() {
    getRequest(API.equipStatus).then(res => {
      if (res && res.length > 0) {
        const resEnum = {}
        res.forEach(element => {
          resEnum[element.name] = element.text
        });
        this.setData({
          equipStatus: res,
          equipStatusEnum: resEnum
        })
      }

    })
  },
  onUploadClick() {
    wx.chooseMedia({
      mediaType: "image",
      count: 1,
      success: (e) => {
        console.log("imageSuccess", e)
        const tempFile = e.tempFiles[0];
        this.setData({
          showAddForm: true
        })
      },
      fail: (e) => {
        this.setData({
          showAddForm: true
        })
      }
    })
  },
  confirmUse(type, item, params) {

    // const item = this.data.currentOperateItem;
    const that = this;
    wx.showLoading({
      title: '数据正在提交',
    })
    return postRequest(API.equipChange, {
      equipName: item.equipName,
      type,
      ...params
    }).then(res => {
      wx.hideLoading();
      that.resetForm();
    })
  },
  bindSearchInput(e) {
    var val = e.detail.value.trim();

    this.setData({
      searchParams: {
        ...this.searchParams,
        searchStr: val
      }
    })
    this.fetchSelectAbleList();
  },

  searchByKeyWords(keyword) {
    wx.request({
      url: app.globalData.host + "",
    })
  },
  bindEndDateChange(e) {
    // console.log("e",e)
    this.setData({
      effectEnd: e.detail.value
    })
  },
  bindStartDateChange(e) {
    // console.log("e",e)
    this.setData({
      effectStart: e.detail.value
    })
  },
  bindDateChange(e) {
    // console.log("e",e)
    this.setData({
      inStockDate: e.detail.value
    })
  },
  /*****************************/
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.equipCateList();
    this.setData({
      searchParams: {
        ...this.searchParams,
        searchStr: ''
      }
    })
    this.fetchSelectAbleList();
    this.hasManagerRolePermission();
  },

  equipCateList() {
    getRequest(API.cateList).then(res => {
      this.setData({
        equipListData: res
      })
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      showAddForm: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})